package com.atguigu.gmall.controller;


import com.atguigu.gmall.entity.CartInfo;
import com.atguigu.gmall.result.RetVal;
import com.atguigu.gmall.service.CartInfoService;
import com.atguigu.gmall.util.AuthContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartInfoService cartInfoService;

    @PostMapping("addToCart/{skuId}/{skuNum}")
    public RetVal addToCart(@RequestParam Long skuId, @RequestParam Integer skuNum, HttpServletRequest request) {
        String userId = this.getUserId(request);// 获取用户Id ，id可能为用户id，也可能未临时的id
        cartInfoService.saveCart(skuId, skuNum, userId); //添加到购物车
        return RetVal.ok();
    }

    @GetMapping("getCartList")
    public RetVal getCartList(HttpServletRequest request){
        String userId = this.getUserId(request);    // 获取用户Id
        List<CartInfo> cartInfoList = cartInfoService.getCartListByUserId(userId);   //获取购物车列表
        return RetVal.ok(cartInfoList);
    }
    // 删除购物车
    @DeleteMapping("deleteCart/{skuId}")
    public RetVal deleteCartInfo(@PathVariable Long skuId,HttpServletRequest request){
        String userId = this.getUserId(request);    // 获取用户Id
        cartInfoService.deleteCartInfo(userId,skuId);
        return RetVal.ok();
    }

    @GetMapping("getSelectedProduct/{userId}")
    public List<CartInfo> getSelectedProduct(@PathVariable String userId){
        return cartInfoService.getSelectedProduct(userId);
    }

    //6.从数据库中查询购物车缓存信息
    @GetMapping("queryFromDbToRedis/{userId}")
    public List<CartInfo> queryFromDbToRedis(@PathVariable String userId){
        return cartInfoService.queryFromDbToRedis(userId);
    }

    private String getUserId(HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        if (StringUtils.isEmpty(userId)){
            // 获取未登录的用户Id
            userId = AuthContextHolder.getUserTempId(request);
        }
        return userId;
    }


}
